<template>
    <div class="left-menu">
        <el-menu
        active-text-color="#fff"
        background-color="#20222A"
        class="el-menu-vertical-demo"
        default-active="/home"
        text-color="#9395A1"
        router
        >
            <el-menu-item index="/home">
                <el-icon><HomeFilled /></el-icon>
                <span>首页</span>
            </el-menu-item>
            <template v-for="menu in menus">
                <template v-if="menu.children">
                    <el-sub-menu :index="''+menu.menu_id">
                        <template #title>
                            <el-icon><Menu /></el-icon>
                            <span>{{ menu.menu_name }}</span>
                        </template>
                        <el-menu-item :index="'/'+sub.url" v-for="sub in menu.children" :key="sub.menu_id">
                            <el-icon><document /></el-icon>
                            <span>{{ sub.menu_name }}</span>
                        </el-menu-item>
                    </el-sub-menu>
                </template>
                <template v-else>
                    <el-menu-item :index="'/'+menu.url">
                        <el-icon><Menu /></el-icon>
                        <span>{{ menu.menu_name }}</span>
                    </el-menu-item>
                </template>
            </template>
        </el-menu>
    </div>
</template>
<script lang="ts" setup>
//路由
const router = useRouter();
//引入elementPlus图标
import { Menu, Document, HomeFilled } from '@element-plus/icons-vue'
//引入菜单API接口
import { getMenus } from '@/api/apis/menu.ts';
//引入工具方法
import { recursionTrees } from '@/utils/tools.ts';
interface Menu {
    menu_id: number //菜单id
    menu_name: string //菜单名称
    icon: string //图标
    url: string //组件路径
    children?: Menu[]
}
//定义菜单数据
let menus = ref<Menu[]>([]);
//查询菜单数据
const handleGetMenus = async () => {
    let res:any = await getMenus({});
    if(res.code === 200) {
        if(res.data.length > 0) {
            //菜单结构转换
            menus.value = recursionTrees(res.data, 'menu_id','parent_id', 0);
        }
    }
}

onMounted(() => {
    router.push('/home');
    handleGetMenus();
});
</script>
<style lang="scss" scoped>
.left-menu {
    width: 100%;
    height: 100%;
    padding: 0 10px;
    .el-menu {
        border-right-color: #20222A;
    }
}
.left-menu :deep(.el-menu-item) {
    height: 40px;
    line-height: 40px;
    border-radius: 6px;
}
.left-menu :deep(.el-menu-item.is-active) {
    background: #303338;
}
</style>